package com.itheima.search.service.impl;

import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.search.document.ArticleInfoDocument;
import com.itheima.search.dto.SearchDto;
import com.itheima.search.service.ArticleInfoDocumentSearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.search.service.impl
 */
@Service
public class ArticleInfoDocumentServiceImpl implements ArticleInfoDocumentSearchService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;




    /**
     * app端文章搜索
     *
     * @param dto
     * @return
     */
    @Override
    public List<ArticleInfoDocument> search(SearchDto dto) {
        //参数校验
        if(null == dto){
            throw new LeadNewsException(HttpCodeEnum.PARAM_REQUIRE);
        }
        // 时间处理
        if(null == dto.getMinBehotTime()){
            dto.setMinBehotTime(new Date());
        }
        //1. 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //isDown=0, isDelete=0 boolQuery(must,must not, should, should not)
        //searchWords, tag=>channelId,  publishTime<=minBehotTime
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.termQuery("isDown", 0))
            .must(QueryBuilders.termQuery("isDelete", 0));
            //.must(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        //tag=>channelId __all__
        if(!"__all__".equals(dto.getTag())){
            boolQuery.must(QueryBuilders.termQuery("channelId", Integer.parseInt(dto.getTag())));
        }
        if(StringUtils.isNotEmpty(dto.getSearchWords())){
            // 有搜索内容
            boolQuery.must(QueryBuilders.matchQuery("title", dto.getSearchWords()));
        }
        queryBuilder.withQuery(boolQuery);

        //2. 分页设置, 使用PageRequest时，要注意，如果是查第1页，page=1
        queryBuilder.withPageable(PageRequest.of(0,dto.getPageSize()));
        //3. 排序
        queryBuilder.withSort(SortBuilders.fieldSort("publishTime").order(SortOrder.DESC));
        //4. 高亮
        // 高亮字段
        queryBuilder.withHighlightFields(new HighlightBuilder.Field("title"));
        queryBuilder.withHighlightBuilder(new HighlightBuilder()
            .preTags("<font color='red'>").postTags("</font>").requireFieldMatch(false));
        NativeSearchQuery query = queryBuilder.build();

        //5. 查询
        SearchHits<ArticleInfoDocument> searchResult = elasticsearchRestTemplate.search(query, ArticleInfoDocument.class);
        //6. 解析结果
        List<SearchHit<ArticleInfoDocument>> searchHits = searchResult.getSearchHits();
        List<ArticleInfoDocument> list = new ArrayList<>();
        for (SearchHit<ArticleInfoDocument> searchHit : searchHits) {
            ArticleInfoDocument articleInfoDocument = searchHit.getContent();
            //7. 解析高亮
            List<String> highlights = searchHit.getHighlightField("title");
            if(!CollectionUtils.isEmpty(highlights)){
                // 有高亮
                String title = String.join(",", highlights); // 多个以逗号分割
                articleInfoDocument.setTitle(title);
            }
            list.add(articleInfoDocument);
        }
        //8. 返回数据
        return list;
    }



}
